<?php  
/* OpenBIBLIO -- A library administration web interface
 * Copyright (C) 2002-2005 Frederic Descamps <lefred@tiscali.be>
 * Copyright (C) 2011-2012 Laurent Luyssen   <big.lol13@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

session_start();
include_once "includes/db.inc";
include_once "includes/functions.inc";
include_once "includes/searchDAO.inc";
include_once "includes/session.inc";

if (!isset($_GET['export'])) {
	include_once ("includes/header.inc");
}
include_once "includes/colCfgDAO.inc";
include_once "includes/resultPagination.inc";

/**
 *
 * @param SearchDAO $dao 
 */
function exportResults($dao) {
	header("Content-Type: text/csv");
	header("Content-disposition: attachment; filename=openbiblio.csv");

	// Write columns names
	$col_cfg = new ColCfgDAO($_SESSION["login"], "export");
	$cols = $col_cfg->getConfig();
	$line = "";
	foreach ($cols as $col) {
		if (!SearchDAO::isAllowedCol($col->db_name))
			continue;
		if ($line == "")
			$line .= "#".$col->db_name;
		else
			$line .= ";".$col->db_name;
	}
	echo $line."\n";

	// Write result data
	$rc = $dao->doSearch(FALSE, TRUE, TRUE);
	if ($rc) {
		while (($row = $dao->getRow()) !== FALSE) {
			$line = "";
			foreach ($cols as $col) {
				if (!SearchDAO::isAllowedCol($col->db_name))
					continue;
				if ($line != "")
					$line .= ";";
				// Replace any occurence of the separator ';' by a ','
				$line .= str_replace(";", ",", $row[$col->db_name]);
			}
			echo $line."\n";
		}
	}
}

$dao = SearchDAO::getInstance();
if (isset($_GET['export'])) {
	exportResults($dao);
	exit();
}
?>

<script type="text/javascript">
function submitform(form_name, column) {
	if (column != '') 
		document.forms[form_name].sort_col.value = column;
	document.forms[form_name].submit();
}

function newPopup(url) {
	popupWindow = window.open(url,'popUpWindow',
'height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no');
}

/*
Simple Image Trail script- inspired By JavaScriptKit.com
Visit http://www.javascriptkit.com for this script and more
This notice must stay intacthttp://www.javascriptkit.com 
*/ 

var w = 1;
var h = 1;
var cover;
var img_width = null;
var img_height = null;
var wait_img = new Image();
wait_img.src = 'images/wait.gif';

function gettrailobj() {
	if (document.getElementById) 
		return document.getElementById("ttimg");
	else if (document.all)
		return document.all.ttimg;
}

function gettrailstyle() {
	return gettrailobj().style;
}

function truebody() {
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function hidetrail() {
	document.onmousemove="";
	gettrailstyle().visibility = "hidden";
}

function showtrail(file, width, height) {
	if(navigator.userAgent.toLowerCase().indexOf('opera') == -1) {
		imageLoaded(wait_img, null, null);
		
		if (typeof(width) == 'undefined')
			width = null;
		if (typeof(height) == 'undefined')
			height = null;
		
		cover = new Image();
		img_width = width;
		img_height = height;
		cover.onload = function() {
			imageLoaded(cover, img_width, img_height);
		};
		cover.src = file;
		if (cover.complete)
			imageLoaded(cover, img_width, img_height);
	}
}

function imageLoaded(img, width, height) {
	gettrailobj().src = img.src;
	var trail = gettrailstyle();
	trail.visibility = "visible";
	
	if ((width == null) && (height == null) ) {
		w = img.width;
		h = img.height;
	}
	else {
		if (width == null) {
			h = height;
			w = Math.round(img.width * h / img.height);
		}
		else if (height == null) {
			w = width;
			h = Math.round(img.height * w / img.width);
		}
		else {
			w = width;
			h = height;
		}
	}
	trail.width = w + "px";
	trail.height = h + "px";
	document.onmousemove=followmouse;
}

function followmouse(e) {
	if(navigator.userAgent.toLowerCase().indexOf('opera') == -1) {
		var xcoord = 20;
		var ycoord = 20;

		if (typeof e != "undefined") {
			xcoord += e.pageX;
			ycoord += e.pageY;
		}
		else if (typeof window.event !="undefined") {
			xcoord += truebody().scrollLeft + event.clientX;
			ycoord += truebody().scrollTop + event.clientY
		}

		var docwidth, docheight;
		if (document.all) {
			docwidth  = truebody().scrollLeft + truebody().clientWidth;
			docheight = Math.max(truebody().scrollHeight, truebody().clientHeight);
		}
		else {
			docwidth  = pageXOffset + window.innerWidth - 15;
			docheight = Math.max(document.body.offsetHeight, window.innerHeight);
		}

		if (xcoord+w+3>docwidth)
			xcoord = xcoord - w - (20*2);

		if (ycoord-truebody().scrollTop+h>truebody().clientHeight)
			ycoord = ycoord - h - 20;

		var trailStyle = gettrailstyle();
		trailStyle.left = xcoord + "px";
		trailStyle.top  = ycoord + "px";
	}
}
</script>

<?php
	include "includes/searchParams.inc";
	
 	$cur_page = 0;
	if ($_SERVER['REQUEST_METHOD'] == 'POST')
		processPostData($dao);
	else {
		if (isset($_GET['page']) && !empty($_GET['page'])) 
			$cur_page = $_GET['page'];
	}	
	displaySearchParams($dao);
	
	$rec_bypage = get_max_record();
    $dao->setRowsPerPage($rec_bypage);
    $dao->setStartRow($cur_page * $rec_bypage);
    if (!$dao->doSearch())
		print "PROBLEME : ".biblio_db_error()."<br>".$dao->getQuery(); 
	else {
		/*
		 * # of results found
		 */
		$total_rows = $dao->getFoundRowCount();
		echo "<CENTER>";                
		echo _("Nombre d'enregistrement(s) trouv&eacute;(s) : ").$total_rows;
		echo "<br/><br/>\n";
		
		/*
		 *  Table header
		 */
		$allowedCols = SearchDAO::getAllowedCols();
		if (isset($_SESSION['login']))
			$login = $_SESSION['login'];
		else
			$login = "";
		$col_cfg = new ColCfgDAO($_SESSION["login"], "search");
		$cols = $col_cfg->getConfig();
		$sort_col   = $dao->getPrimarySortColumn();
		$sort_order = $dao->getPrimarySortOrder();
        if ($sort_order == DBSortOrder::desc)
			$img = '<img src="images/arrow_down.gif"/>';
        else
			$img = '<img src="images/arrow_up.gif"/>';
				
		echo "<TABLE class=\"search_results\">\n<TR>";
		foreach ($cols as $col) {
			if (!SearchDAO::isAllowedCol($col->db_name))
				continue;
			echo '<th><a href="javascript:submitform(\'search_form\', \''.$col->db_name.'\')">';
			echo $allowedCols[$col->db_name];
			if ($sort_col == $col->db_name)
				echo $img;
			echo '</a></th>';
		}

		if (!empty($login)) 
			echo "<th>"._("Action")."</th>";
		echo "</tr>";
        
		/*
		 * Results
		 */
		$i=0;
		while ($row = $dao->getRow()) {      
            $i++;
            $liv_id = $row['id'];                                            	
            // Check if book is already borrowed            
			if (isset($row['emprunteur'])) {
				$style = "borrowed";
			}
			else {
				if ($i%2 == 1)
					$style = "odd";
				else 
					$style = "even";
			}						
            echo "\n<tr class=\"$style\"";
			if (!empty($row['cover_url']) && (strtolower($row['cover_url']) != 'null')) {
				echo " onmouseover=\"showtrail('".$row['cover_url']."');\" onmouseout=\"hidetrail();\" >";
			}
			else
				echo ' onmouseover="hidetrail();" >';
			foreach ($cols as $col) {
				if (!SearchDAO::isAllowedCol($col->db_name))
					continue;
				$link = "JavaScript:newPopup('resume.php?id=".$liv_id."');";
				echo '<td><a href="'.$link.'">'.$row[$col->db_name].'</a></td>';
			}
			
            if (!empty($login)) {
				echo '<TD align="center">';
				echo "<A HREF=\"JavaScript:newPopup('admin.php?user=".$login."&action=mod&type=livre&id=".$liv_id."');\">";
				echo '<img src="images/b_edit.png" alt="'._("Editer").'" title="'._("Editer").'"></A>';
				echo "&nbsp;<A HREF=\"JavaScript:newPopup('admin.php?user=".$login."&action=del&type=livre&id=".$liv_id."');\">";
				echo '<img src="images/b_delete.png" alt="'._("Effacer").'" title="'._("Effacer").'"></A>';
				if (!isset($row['emprunteur'])) {
					echo "&nbsp;<A HREF=\"JavaScript:newPopup('pret_out.php?id=".$liv_id."');\">";
					echo '<img src="images/book_out.png" alt="'._("Pr&ecirc;ter").'" title="'._("Pr&ecirc;ter").'"></A>';
				}
				else {
					echo "&nbsp;<A HREF=\"JavaScript:newPopup('pret_in.php?id=".$liv_id."');\">";
					echo '<img src="images/book_in.png" alt="'._("Retour").'" ';
					echo 'title="'._("Retour (Pr&ecirc;t&eacute; &agrave; ").$row['emprunteur'].')"></A>';
				}
				echo '</TD>';
			}
			echo "</tr>\n";
		}
		echo "</TABLE><br>";
		
 		/*
		 * Pagination
		 */
		if (($rec_bypage > 0) && ($total_rows > $rec_bypage) ) {
			$last_page = ceil($total_rows / $rec_bypage);
			$pagination = new ResultPagination('search.php?page=$PAGE', $cur_page, $last_page);
			echo $pagination->toHtml();
		}
		echo "</CENTER>";
	} 
	$dao->saveToSession();

?>
<br/><br/>
<div>
	<span id=left-text>
		<A HREF="index.php"><?php echo _("retour menu principal"); ?></A>
	</span>
</div>

<?php if ($total_rows > 0) { ?>
<div>
	<span id=right-text>
		<A HREF="search.php?export=csv"><?php echo _("Exporter ce r&eacute;sultat"); ?></A>
	</span>
</div>

<br/>
<!-- Book cover -->
<img id="ttimg" src="images/wait.gif" style="position:absolute;visibility:hidden;left:0px;top:-1000px;width:1px;height:1px;border-style:solid;border-width:1px;border-color:black;"/>
<?php
}
include("includes/footer.inc");
?>
